#include "client.h"

DEFINE_string(protocol, "baidu_std", "Protocol type. Defined in src/brpc/options.proto");
DEFINE_string(search_attachment, "foo", "Carry this along with requests");
DEFINE_string(connection_type, "", "Connection type. Available values: single, pooled, short");
DEFINE_string(search_server, "0.0.0.0:9999", "IP Address of server");
DEFINE_string(load_balancer, "", "The algorithm for load balancing");
DEFINE_int32(timeout_ms, 3000, "RPC timeout in milliseconds");
DEFINE_int32(max_retry, 3, "Max retries(not including the first RPC)"); 
DEFINE_int32(interval_ms, 5000, "Milliseconds between consecutive requests");
DEFINE_string(http_content_type, "application/json", "Content type of http request");

Client::Client(){
    options.protocol = FLAGS_protocol;
    options.connection_type = FLAGS_connection_type;
    options.timeout_ms = FLAGS_timeout_ms;
    options.max_retry = FLAGS_max_retry;
    channel.Init(FLAGS_search_server.c_str(),FLAGS_load_balancer.c_str(),&options); 
}
vector<News_Info> Client::Return(string keyword){
     // Normally, you should not call a Channel directly, but instead construct
        // a stub Service wrapping it. stub can be shared by all threads as well.
    SG::Service_Stub stub(&channel);
    
    SG::Request req;
    SG::Response resp;
    brpc::Controller cntl;
    
    req.set_keyword(keyword);
    
    if (FLAGS_protocol != "http" && FLAGS_protocol != "h2c")  {
        // Set attachment which is wired to network directly instead of 
        // being serialized into protobuf messages.
        cntl.request_attachment().append(FLAGS_search_attachment);
    } else {
        cntl.http_request().set_content_type(FLAGS_http_content_type);
    }
    
    // Because `done'(last parameter) is NULL, this function waits until
    // the response comes back or error occurs(including timedout).
    stub.Search(&cntl, &req, &resp, NULL);
    vector<News_Info> v;
    if (!cntl.Failed()) {
        //写回数据给客户端
        for(auto i: resp.info()){
            News_Info info(i.title(),i.author(),i.date());
            v.push_back(info);
        }
    }else 
        LOG(WARNING) << cntl.ErrorText();

    return v;
}
